package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx/ziface"
)

/*
	连接管理模块
*/

type ConnManager struct {

	//管理的连接集合
	connections map[uint32]ziface.IConnection

	//保护连接集合的读写锁
	connLock sync.RWMutex
}

// NewConnManager 创建当前连接的方法
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

// Add 添加连接
func (connMgr *ConnManager) Add(conn ziface.IConnection) {
	//保护共享资源map ,加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	//将conn 加入到connmanager 中
	connMgr.connections[conn.GetConnectionID()] = conn

	fmt.Println("connID = ", conn.GetConnectionID(), "add connection add to connmanager  successfully : conn num = ", connMgr.Len())
}

// Remove 删除连接
func (connMgr *ConnManager) Remove(conn ziface.IConnection) {
	//保护共享资源map ,加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	//删除链接
	delete(connMgr.connections, conn.GetConnectionID())
	fmt.Println("connID = ", conn.GetConnectionID(), "delete connection from connmanager  successfully : conn num = ", connMgr.Len())
}

// 根据connID 获取连接
func (connMgr *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	//保护共享资源map ,加写锁
	connMgr.connLock.RLock()
	defer connMgr.connLock.RUnlock()

	if conn, ok := connMgr.connections[connID]; ok {
		//找到了
		return conn, nil
	} else {
		return nil, errors.New("connection is not found ")
	}
}

// 得到当前的连接总数
func (connMgr *ConnManager) Len() int {
	return len(connMgr.connections)
}

// 清楚或终止所有连接
func (connMgr *ConnManager) ClearConn() {
	//保护共享资源map ,加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	//删除conn 饼停止conn 的工作
	for connID, conn := range connMgr.connections {
		//停止
		conn.Stop()
		//删除
		delete(connMgr.connections, connID)
	}

	fmt.Println("clear all connection successfully ! conn num = ", connMgr.Len())
}
